from multineuro.game import Game
from tom.configuration import SET_OF_SPRITES_CONFIGS, TUIO_ENABLE, FULLSCREEN
from tom.screen import Screen
import logging
import time
from multineuro.forms.forms import Form
from multineuro.forms.input import Input


logging.basicConfig(level=logging.INFO, format='%(levelname)s:\t%(message)s')


class Logger(object):


    def start(self, filename):
        tstamp = str(time.time())
        self.file = open(tstamp + ' - ' + filename + '.out', 'w')

    def save_answer(self, trial, value):
        self.file.write('\t'.join((trial, value)) + '\n')
        self.file.flush()

    def finalize(self):
        self.file.close()



class TheoryOfMind(Game):



    def _start_trials(self):
        self.current_screen = 0
        self.screens[self.current_screen].show()

    def initialize_screens(self):
        root = True
        self.screens = []
        for conf in SET_OF_SPRITES_CONFIGS:
            current_screen = Screen(conf, self._end_screen, self.logger, root)
            self.screens.append(current_screen)
            for sprite in current_screen.sprites():
                self.add_active_sprite(sprite)
        self._start_trials()

    def process_form(self, form_result):
        self.logger.start(form_result['Name'] + '.tom')
        self._start_trials()



    def initialize_form(self):
        form = Form(True)
        form.add_object('Name', Input('Nombre', '',
                                      label_size=18,
                                      input_border_color=(255, 100, 100),
                                      input_border_width=0,
                                      input_bg_color=(0, 0, 0, 0)))
        self.registerForm(form, self.process_form)

    def __init__(self):
        super(self.__class__, self).__init__("Theory of Mind",
                                             fullscreen=FULLSCREEN,
                                             tuio=TUIO_ENABLE)
        self.logger = Logger()
        self.initialize_screens()
        self.initialize_form()


    def _end_screen(self):
        self.screens[self.current_screen].hide()
        self.current_screen += 1
        if self.current_screen < len(self.screens):
            self.screens[self.current_screen].show()
        else:
            self.logger.finalize()
            self.game_over()



def main():
    """ Game"""
    exp = None
    error = False
    try:
        exp = TheoryOfMind()
        exp.start()
    except Exception:
        error = True
        raise
    finally:
        if error and exp:
            exp.close()


if __name__ == '__main__':
    main()
